import { Registry } from '../registry';

type AIEngine = {
  version: string;
  process: (input: any) => Promise<any>;
  capabilities: Set<string>;
};

export class AIEngineRouter {
  private engines: Map<string, AIEngine> = new Map();
  private registry: Registry;

  constructor(registry: Registry) {
    this.registry = registry;
  }

  registerEngine(engine: AIEngine) {
    this.engines.set(engine.version, engine);
    this.registry.register(`ai-engine:${engine.version}`, engine);
  }

  async getOptimalEngine(capabilities: string[]): Promise<AIEngine> {
    // 按版本降序排序
    const sortedVersions = Array.from(this.engines.keys())
      .sort((a, b) => b.localeCompare(a));

    // 查找满足所有需求的最高版本
    for (const version of sortedVersions) {
      const engine = this.engines.get(version)!;
      if (capabilities.every(cap => engine.capabilities.has(cap))) {
        return engine;
      }
    }

    // 降级到支持最多功能的版本
    let bestMatch: { engine: AIEngine; score: number } | null = null;
    for (const [_, engine] of this.engines) {
      const score = capabilities.filter(c => engine.capabilities.has(c)).length;
      if (!bestMatch || score > bestMatch.score) {
        bestMatch = { engine, score };
      }
    }

    if (!bestMatch) throw new Error('No compatible AI engine found');
    return bestMatch.engine;
  }

  async process(input: any, requiredCapabilities: string[] = []): Promise<any> {
    const engine = await this.getOptimalEngine(requiredCapabilities);
    return engine.process(input);
  }
}